package main

import (
	"flag"
	"fmt"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"github.com/nacos-group/nacos-sdk-go/inner/uuid"
	"go.uber.org/zap"
	"net"
	"os"
	"os/signal"
	"service_base_shop_api/goods_web/global"
	"service_base_shop_api/goods_web/initialize"
	"service_base_shop_api/goods_web/utils/register/consul"
	myvalidator "service_base_shop_api/goods_web/validator"
	"syscall"
)
func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, err
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port,  nil
}

func main()  {

	//IP := flag.String("ip", "0.0.0.0", "ip地址")
	Port := flag.Int("port", 0, "端口号")
	flag.Parse()
	if *Port == 0{
		*Port, _ = GetFreePort()
	}

	//1. 初始化logger
	initialize.InitLogger()

	//2.初始化配置文件
	initialize.InitConfig()

	//3初始化router
	Router := initialize.InitRouter()

	//4.注册远程服务
	initialize.InitGoodsSrvConn()

	//注册自定义验证器
	if  err := initialize.InitTrans("zh");err != nil{
		panic(err)
	}
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("tel", myvalidator.ValidateMobile)
		//如果是翻译
		_ = v.RegisterTranslation("tel", global.Trans, func(ut ut.Translator) error {
			return ut.Add("tel", "{0} 非法的手机号码!", true) // see universal-translator for details
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("tel", fe.Field())
			return t
		})
	}
	service_id,_ := uuid.NewV4()
	serviceId := fmt.Sprintf("%s", service_id)
	register_client := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host,global.ServerConfig.ConsulInfo.Port)
	if  err := register_client.Register(global.ServerConfig.Host,*Port,global.ServerConfig.Name,[]string{"goods","goods_web"},serviceId); err != nil{
		zap.S().Panic("服务注册失败:", err.Error())
	}

	zap.S().Info(fmt.Sprintf("启动服务端口:%d",*Port))

	go func() {
		if err := 	Router.Run(fmt.Sprintf(":%d",*Port));  err != nil {
			zap.S().Panic("启动失败:", err.Error())
		}
	}()


	quit := make(chan  os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err :=  register_client.DeRegister(serviceId); err != nil {
		zap.S().Info("注销失败:", err.Error())
	}else {
		zap.S().Info("注销成功")
	}
}
